package com.itjh.service.impl;

import com.itjh.mapper.DeptMapper;
import com.itjh.mapper.EmpMapper;
import com.itjh.pojo.Dept;
import com.itjh.pojo.DeptLog;
import com.itjh.service.DeptLogService;
import com.itjh.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;
    @Override
    public List<Dept> selectAll() {
        List<Dept> depts = deptMapper.selectAll();
        return depts;
    }

    /**
     * 根据部门id，删除部门信息及部门下的所有员工
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Integer deptId) {
        try {
            int i = deptMapper.deleteById(deptId); //根据部门id删除部门信息
//            int a = 1/0;
            int i1 = empMapper.deleteByDeptId(deptId);//删除部门下的所有员工信息

            return i;
        } finally {
            //记录操作日志
            deptLogService.insert(new DeptLog(null, LocalDateTime.now(), "执行了解散部门操作，此次解散的部门是 "+deptId + " 号部门"));
        }
    }

    @Override
    public int insertDept(Dept dept) {
        // 给dept对象补充两个数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.insertDept(dept);
    }

    @Override
    public Dept getById(Integer deptId) {
        Dept dept = deptMapper.getById(deptId);
        return dept;
    }

    @Override
    public int updateDeptById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        int i = deptMapper.updateDeptById(dept);
        return i;
    }
}
